package cn.dataling.dag.util;


import java.sql.*;

/**
 * 数据库工具类
 * jdbc4.0之后不需要显式的去加载驱动，如果驱动包符合 SPI 模式就会自动加载
 */
public class JdbcUtil {

    /**
     * 测试数据源连通性
     *
     * @param username 用户名
     * @param password 密码
     */
    public static void connect(String url, String username, String password) {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static Integer getCount(String url, String dbName, String username, String password, String table, String type) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            con = DriverManager.getConnection(url, username, password);
            String sql = "SELECT COUNT(*) FROM " + table;
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (con != null) con.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        return 0;
    }
}
